//
//  HMComposeTextView+Extension.swift
//  MicroBlog
//
//  Created by Apple on 16/10/7.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

extension HMComposeTextView {
    //通过富文本获取文本内容
    var emoticonText: String {
        var result = ""
        self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in
            if let attachment = info["NSAttachment"] as? HMTextAttachment {
                //能够获取文本附件,表示是图片
                let chs = attachment.emoticon?.chs
                result += chs!
            } else {
                //没有图片,纯文本
                //通过范围截取富文本的文本内容
                let text = self.attributedText.attributedSubstring(from: range).string
                result += text
            }
        }
        return result
    }
    
    func insertEmoticon(emoticon: HMEmoticon){
        if emoticon.type == "0" {
            //            let chs = emoticon.chs
            //            textView.insertText(chs!)
            //图片转成富文本
            //记录上一次的富文本
            let lasAttributedString = NSMutableAttributedString(attributedString: self.attributedText)
            //
            let attributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: self.font!)
            //添加本次富文本
            //            lasAttributedString.append(attributedStr)
            //获取文本选中的范围
            var selectedRange = self.selectedRange
            lasAttributedString.replaceCharacters(in: selectedRange, with: attributedStr)
            //设置富文本的字体
            lasAttributedString.addAttribute(NSFontAttributeName,value: self.font!, range: NSMakeRange(0, lasAttributedString.length))
            //4.设置富文本
            self.attributedText = lasAttributedString
            //修改选中位置的光标,每次点击表情光标位置+1
            selectedRange.location += 1
            //修改选中范围长度为0
            selectedRange.length = 0
            //设置textView的选中光标范围
            self.selectedRange = selectedRange
            //发送文字改变的通知
            //添加富文本系统不会发送文字改变的通知
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            //textView的代理方法此时也不会调用,需要手动调用
            // "?" 先判断代理方法是否实现,如果实现直接调用,否则返回nil
            self.delegate?.textViewDidChange?(self)
        } else {
            let emoji = (emoticon.code! as NSString).emoji()
            self.insertText(emoji!)
        }
    }
}
